<template>
  <!-- 用户隐私协议-->
  <uni-popup
    ref="showPrivacy"
    :animation="false"
    :is-mask-click="false"
  >
    <div
      v-for="item in dialogData"
      :key="item.id"
      class="privacyAgreement_popup"
    >
      <div class="popup__title">{{ item.title }}</div>
      <div class="popup__tips">{{ item.desc1 }}</div>
      <div class="popup__urlTitle" @tap.stop="openPrivacyContract">{{ item.urlTitle }}</div>
      <div class="popup__tips">{{ item.desc2 }}</div>
      <div class="popup_btn">
        <button
          id="disagree-btn"
          class="weui-btn btn"
          @tap.stop="handleDisagree"
        >
          取消
        </button>
        <button id="agree-btn"
                class="weui-btn btn1"
                open-type="agreePrivacyAuthorization"
                @agreeprivacyauthorization="handleAgree"
        >
          同意
        </button>
      </div>
    </div>
  </uni-popup>
  <scroll-view>
    <div class="wrap">
      <!--  跳转其他小程序  -->
      <Popup ref="otherAppRef">
        <Confirm
          title="是否跳转到 收稻CPM ？"
          @no="cancelOtherApp"
          @ok="toOtherApp"
        />
      </Popup>
      <!-- 服务协议及隐私保护 -->
      <Popup ref="agreementPrivacyRef" mask>
        <Pconfirm cancel-text="不同意" confirm-text="同意" tip-title="服务协议及隐私保护" @cancel="disAgreeFn" @confirm="agreeFn">
          <template #tip>
            <div>
              为了更好地保障您的合法权益，请阅读并同意以下协议
              <span style="color: #1890FF;" @tap.stop="readDeal('用户服务协议')">《用户服务协议》</span>
              及
              <span style="color: #1890FF;" @tap.stop="readDeal('隐私政策')">《隐私政策》</span>
            </div>
          </template>
        </Pconfirm>
      </Popup>
      <!--   输入密码错误次数超过三次   -->
      <Popup ref="pwdErrRef" mask>
        <Pconfirm :is-two-btn="false" confirm-text="我知道了" tip-text="您的密码多次错误，如您忘记密码，请使用手机验证码登录，并重置密码" tip-title="提示" @confirm="pwdErrRef.change()" />
      </Popup>
      <div class="login_bg_icon"><Image height="294" name="login_zhike" oss type="png" width="300" /></div>
      <div class="logo_form">
        <div class="logo_title">{{ loginTitle }}</div>
        <div class="logo_tips">{{ loginTips }}</div>
        <div style="width: 100%; margin-top: 62rpx;">
          <u--form :label-style="{fontSize: '36rpx'}">
            <u-form-item border-bottom label="+86">
              <u--input
                v-model="form.username"
                border="none"
                font-size="36rpx"
                maxlength="11"
                placeholder="请输入手机号"
              />
            </u-form-item>
            <u-form-item v-if="loginMode === 0" border-bottom label="密码">
              <u--input
                v-if="isPassword"
                v-model="form.password"
                border="none"
                clearable
                font-size="36rpx"
                placeholder="请输入密码"
                type="password"
              >
                <template #suffix>
                  <Icon :styles="{opacity: '0.25'}" name="icon-biyanjing" size="40" @tap.stop="isPassword= !isPassword" />
                </template>
              </u--input>
              <u--input
                v-else
                v-model="form.password"
                border="none"
                clearable
                font-size="36rpx"
                placeholder="请输入密码"
                type="text"
              >
                <template #suffix>
                  <Icon :styles="{opacity: '0.25'}" name="icon-yanjing" size="40" @tap.stop="isPassword= !isPassword" />
                </template>
              </u--input>
            </u-form-item>
          </u--form>
        </div>
        <S_Button v-if="loginMode === 1" :disabled="!canDeal" :style="{marginTop: '102rpx'}" size="L" @confirm="getVcode">发送验证码</S_Button>
        <S_Button v-if="loginMode === 0" :disabled="!canDeal" :style="{marginTop: '48rpx'}" size="L" @confirm="login">登录</S_Button>
      </div>
      <div class="login_mode" @tap="changeLoginMode">{{ loginModeBtn }}</div>
      <div class="read_sign">
        <div class="touch_area" @tap="touchFn">
          <Switch ref="switchRef" size="SS" type="box" @value="canDeal = $event" />
        </div>
        <div :style="{marginLeft: '10rpx', display: 'flex'}">
          我已阅读并同意
          <span class="base_color" @tap.stop="readDeal('用户服务协议')">《用户服务协议》</span>
          及
          <span class="base_color" @tap.stop="readDeal('隐私政策')">《隐私政策》</span>
        </div>
      </div>
    </div>
    <div class="ai_chat flex_sb_cen">
      <div v-show="isShowAiTip" class="bubble">
        <div>如果您遇到使用问题，可以随时问我哦。</div>
        <div class="base_color mt10" @tap="isShowAiTip = false">我知道了</div>
        <div class="triangle_black" />
        <div class="triangle_white" />
      </div>
      <div class="ai_avatar">
        <Image name="ai/ai_chat" oss size="120" type="png" @tap="goAIChatFn" />
        <div class="ai_chat_text">AI客服</div>
      </div>
    </div>
  </scroll-view>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { Msg, MsgLoading } from '@C/Msg'
import S_Button from '@C/Button.vue'
import Image from '@C/Image.vue'
import Switch from '@C/Switch.vue'
import { newSendSms, oldSendSms } from '@P/Login/requset'
import { AccountInitialization } from '@U/Auth'
import { LStorage, LStorageClear, onLoad, onShow, onHide, Router, storeCommit, storeState } from '@U/common'
import previewFile from '@U/previewFile'
import Popup from '@C/Popup.vue'
import Confirm from '@C/Confirm.vue'
import goOtherWX from '@U/goOtherWX'
import Pconfirm from '@C/Pconfirm.vue'
import Icon from '@C/Icon.vue'
import { hasMeiDaoAIAccount, partner_login_reg } from './Partner'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line import/no-absolute-path
import envConfig from '/app_build_env/env_config.json'

const switchRef = ref()
const touchFn = () => switchRef.value.changeSwitchMore()

const isPassword = ref(true)

// 隐私协议弹框
const showPrivacy = ref()
onLoad(async (res:any) => {
  if (Object.keys(storeState.toOtherAppParams).length) {
    return setTimeout(() => { otherAppRef.value.change() }, 1000)
  }
  await AccountInitialization()
  // 微信扫邀请码才会进入此逻辑
  if (res.scene) {
    const scene = decodeURIComponent(res.scene)
    if (!/md_qrcode=/.test(scene)) return Msg({ icon: 'error', msg: '这个邀请码我们用不了哦，请换成美稻AI邀请码哦~' })
    const regWay = scene ? 1 : 0
    const inviteCode = scene.split('md_qrcode=')[1]
    storeCommit('meiDaoAI_invite_params', { regWay, inviteCode })
  }
})
// 气泡弹窗倒计时
const isShowAiTip = ref(false)
let interId = 0
const countdownFn = () => {
  let time = 0
  interId = setInterval(() => {
    time += 1
    if (time > 120) {
      clearInterval(interId)
      isShowAiTip.value = true
    }
  }, 1000)
}
const goAIChatFn = () => {
  Router.push('ai_chat')
}
onShow(() => {
  countdownFn()
  getPrivacySetting()
  // LStorageClear('shoudao_prm_reg_type')
})
// 页面隐藏清除定时器
onHide(() => {
  isShowAiTip.value = false
  clearInterval(interId)
})
const getPrivacySetting = () => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  if (wx.getPrivacySetting) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    wx.getPrivacySetting({
      success: (res: { needAuthorization: any; privacyContractName: any; }) => {
        console.log('是否需要授权：', res.needAuthorization, '隐私协议的名称为：', res.privacyContractName)
        if (res.needAuthorization) {
          showPrivacy.value.open()
        }
      },
      fail: () => { },
      complete: () => { },
    })
  }
}

// 隐私协议提示信息
const dialogData = [{
    id: 1,
    title: '用户隐私保护提示',
    desc1: '为了更好地保障您的合法权益，请阅读并同意以下协议。',
    urlTitle: '《美稻AI小程序隐私保护指引》',
    desc2: '我会根据您使用服务的具体功能，对您的个人信息进行收集、使用和共享，请仔细阅读并确认协议内容。',
    innerShow: false,
  }]

// 同意
const handleAgree = () => {
  showPrivacy.value.close()
}

// 取消
const handleDisagree = () => {
  showPrivacy.value.close()
  // setTimeout(() => { showPrivacy.value.open() }, 300)
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  if (wx.exitMiniProgram) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    wx.exitMiniProgram({})
  }
}

// 查看用户隐私协议
const openPrivacyContract = () => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  wx.openPrivacyContract({
    success: (res: any) => {
      console.log('openPrivacyContract success')
    },
    fail: (res: any) => {
      console.error('openPrivacyContract fail', res)
    },
  })
}

// 是否跳转其他小程序
const otherAppRef = ref()
const toOtherApp = () => {
  const params = JSON.parse(JSON.stringify(storeState.toOtherAppParams))
  cancelOtherApp()
  setTimeout(() => {
    goOtherWX(envConfig.partner_weixin_appid, 'pages/Login/Login', params)
  }, 300)
}
const cancelOtherApp = () => {
  storeCommit('toOtherAppParams', {})
  otherAppRef.value.change()
}

// 是否同意协议
const canDeal = ref(false)
const readDeal = (fileName: string) => previewFile(`${import.meta.env.VITE_SHOUDAO_OSS_URL}/document_doc/${fileName}.docx`)

// 登录模式
const loginMode = ref(<0 | 1>1)
const loginModeBtn = computed(() => (loginMode.value ? '密码登录' : '验证码登录'))
const loginTitle = computed(() => (loginMode.value ? '手机验证码登录' : '账号密码登录'))
const loginTips = computed(() => (loginMode.value ? '首次登录请使用手机号验证码登录，仅限于合作伙伴使用' : '如您已设置登录密码，可使用密码登录'))
const changeLoginMode = () => { loginMode.value = loginMode.value ? 0 : 1 }

// 手机号合法化
const mobileLegalize = (t: string) => {
  const reg_dev = /^1[3456789]\d{9}$/
  const reg_pro = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/
  if (!t) {
    Msg({ icon: 'error', msg: '请输入手机号' })
    return false
  }
  if (!(import.meta.env.PROD ? reg_pro : reg_dev).test(t)) {
    Msg({ icon: 'error', msg: '手机号不合法' })
    return false
  }
  return true
}
// 登录表单
const form = reactive({
  username: '',
  password: '',
})
const agreementPrivacyRef = ref()
const disAgreeFn = () => agreementPrivacyRef.value.change()
const agreeFn = () => {
  agreementPrivacyRef.value.change()
  switchRef.value.changeSwitchMore()
  loginMode.value === 1 ? getCodeCommon() : loginCommon()
}
const getCodeCommon = async () => {
  storeCommit('loginForm', {
    username: form.username,
    type: 'vcode',
  })
  await MsgLoading('发送中')
  // 判断是否新账号
  const hasAccount = await hasMeiDaoAIAccount(form.username)
  // 新账号
  if (!hasAccount) {
    storeCommit('isNewAccount', true)
    // 自动注册为个人类型
    // LStorage('shoudao_prm_reg_type', '个人')
    const { code } = await newSendSms(form.username).finally(() => {})
    if (code === 200) {
      uni.hideLoading()
      Router.push('VCodeLogin')
    }
  } else {
    storeCommit('isNewAccount', false)
    const { code } = await oldSendSms(form.username).finally(() => {})
    if (code === 200) {
      uni.hideLoading()
      Router.push('VCodeLogin')
    }
  }
}
// 发送验证码
const getVcode = () => {
  if (!mobileLegalize(form.username)) return
  if (!canDeal.value) return agreementPrivacyRef.value.change()
  getCodeCommon()
}
const pwdErrRef = ref()
const loginCommon = async () => {
  storeCommit('loginForm', {
    username: form.username,
    password: form.password,
    type: 'pwd',
  })
  await partner_login_reg()
  if (storeState.pwdErrCount > 3) pwdErrRef.value.change()
}
// 登录
const login = () => {
  if (!mobileLegalize(form.username)) return
  if (!form.password && loginMode.value === 0) return Msg({ icon: 'error', msg: '请输入密码' })
  if (!canDeal.value) return agreementPrivacyRef.value.change()
  loginCommon()
}
</script>

<style lang="less" scoped>
.privacyAgreement_popup {
  width: 100%;
  height: 600rpx;
  background: #FFFFFF;
  border-radius: 32rpx 32rpx 0rpx 0rpx;
  position: fixed;
  left: 0;
  bottom: 0;
  padding: 0 40rpx;
  .popup__title {
    font-weight: 700;
    text-align: center;
    margin: 30rpx 0;
  }
  .popup__urlTitle {
    color: #1890FF;
    margin: 20rpx 0;
    text-align: center;
  }
  .popup_btn {
    margin: 40rpx auto 0;
    width: 100%;
    display: flex;
    justify-content: space-around;
    .btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #FFFFFF;
      color: #1890FF;
      border-radius: 40rpx;
      margin-top: 30rpx;
      border: 2rpx solid #1890FF;
    }
    .btn1 {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #1890FF;
      border-radius: 40rpx;
      color: #FFFFFF;
    }
  }
}
.wrap {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 66rpx 60rpx;
  background: white;

  .login_bg_icon {
    flex: 0 0 396rpx;
    padding-top: 34rpx;
  }
  .logo_form {
    //height: 430rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .logo_title {
      width: 100%;
      height: 66rpx;
      font-size: 48rpx;
      opacity: 0.85;
      margin-bottom: 2rpx;
    }
    .logo_tips {
      width: 100%;
      height: 34rpx;
      font-size: 28rpx;
      opacity: 0.45;
    }
  }
  .login_mode {
    opacity: 0.45;
    font-size: 28rpx;
    margin: 36rpx 0;
  }
  .read_sign {
    width: 100%;
    font-size: 24rpx;
    color: #a4a4a4;
    display: flex;
    align-items: center;
    .touch_area {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 56rpx;
      height: 56rpx;
    }
  }
}
.mobile {
  height: 86rpx;
  width: 620rpx;
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
  .label {
    font-size: 36rpx;
    width: 120rpx;
  }
  .line {
    height: 28rpx;
    width: 2rpx;
    background: rgba(0, 0, 0, 0);
  }
  .content {
    flex: 1 1;
  }
}
.ai_chat {
  position: fixed;
  right: 20rpx;
  bottom: 200rpx;
  height: 160rpx;
  .bubble {
    position: relative;
    width: 330rpx;
    padding: 12rpx;
    font-size: 28rpx;
    border: 4rpx solid rgba(209, 209, 209, 1);
    border-radius: 16rpx;
    margin-right: 30rpx;
    background-color: #fff;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.25);
    .triangle_black {
      position: absolute;
      width: 0;
      height: 0;
      right: -20rpx;
      top: 35%;
      border-top: 10rpx solid transparent;
      border-bottom: 10rpx solid transparent;
      border-left: 20rpx solid rgba(209, 209, 209, 1);
    }
    .triangle_white {
      position: absolute;
      width: 0;
      height: 0;
      right: -12rpx;
      top: 35%;
      border-top: 10rpx solid transparent;
      border-bottom: 10rpx solid transparent;
      border-left: 20rpx solid #FFFFFF;
    }
  }
  .ai_avatar {
    position: relative;
    .ai_chat_text {
      position: absolute;
      bottom: 0;
      left: 20rpx;
      width: 78rpx;
      height: 35rpx;
      font-size: 20rpx;
      text-align: center;
      line-height: 35rpx;
      border-radius: 35rpx;
      background-color: #ffffff;
      box-sizing: border-box;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.25);
    }
  }
}
</style>
